package com.demo.sbaclient.config;

import com.demo.sbaclient.enums.CacheEnum;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author lijun
 */
@EnableCaching
@Configuration
public class CaffeineCacheConfig extends CachingConfigurerSupport {

    @Bean
    @Override
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        // Caffeine 默认配置
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                .initialCapacity(100)
                // 最后一次写入后经过固定时间过期
                .expireAfterWrite(10, TimeUnit.MINUTES)
                // 缓存的最大条数
                .maximumSize(1000)
                .recordStats();

        cacheManager.setCaffeine(caffeine);

        // 设置缓存名称（可选），只有位于设置集合中的缓存才会生效，否则会报错
        cacheManager.setCacheNames(Arrays.stream(CacheEnum.values()).map(Enum::name).collect(Collectors.toList()));

        // 自定义缓存
        cacheManager.registerCustomCache("testCache", caffeine.build());

        return cacheManager;
    }

}